//
//  ZCProjectdetailsVC.m
//  zctx
//
//  Created by apple on 15/10/8.
//  Copyright © 2015年 sanliang. All rights reserved.


#import "ZCProjectdetailsVC.h"
#import "ZCLookResultVC.h"

@interface ZCProjectdetailsVC ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UIsharePopoverListViewDelegate,ClockLookresultDelegate>
@end

@implementation ZCProjectdetailsVC

@synthesize tableView = _tableView,collectionView = _collectionView,titlenameLable = _titlenameLable,pid =_pid;

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    
    self.navigationItem.title = @"项目详情";
    self.view.backgroundColor = [UIColor whiteColor];
    
    datadictionary = [NSMutableDictionary dictionaryWithCapacity:0];
    sponsorArray = [NSMutableArray arrayWithCapacity:0];
    [self initnavegation]; //导航栏
    
    [self requestProjectdetailsdata];//请求项目详情数据
    [self requestSupporterdata]; //请求支持者数据
    
    [self initTableView];
    [self initTableViewHeaderView];
    
    [self initcollectionView];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCprojectdetailinfoCell" bundle:nil] forCellReuseIdentifier:@"info"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCProjectResultCell" bundle:nil] forCellReuseIdentifier:@"result"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCProjectdetailallinfoCell" bundle:nil] forCellReuseIdentifier:@"allinfo"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCProjectdetailSamplingCell" bundle:nil] forCellReuseIdentifier:@"sampling"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCProjectdetailSamplingTwoCell" bundle:nil] forCellReuseIdentifier:@"samplingtwo"];
}

#pragma mark 导航栏
-(void)initnavegation{
    
    UIButton * rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 24, 22);
    [rightButton setImage:[UIImage imageNamed:@"main_share"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(shareButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * barButtonItem_rightNavBar = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = barButtonItem_rightNavBar;
    
    UIButton * leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 19, 36);
    [leftButton setImage:[UIImage imageNamed:@"navigation_back"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * barButtonItem_leftNavBar = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = barButtonItem_leftNavBar;
}

-(void)backButtonPressed{
    ProgressDismiss;
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 请求项目详情数据
-(void)requestProjectdetailsdata{
    ProgressHUDStr;
    
    NSLog(@"ssspid = %@",_pid);
    [NetworkManager requestFoundingGetOneWithId:_pid Mid:UserModel.mid password:UserModel.password success:^(NSDictionary *dictResponse) {
        ProgressDismiss;
        datadictionary = [dictResponse mutableCopy];
        
          NSLog(@"ssscount  = %ld",[datadictionary count]);
        self.titlenameLable.text = [NSString stringWithFormat:@"%@",[datadictionary objectForKey:@"pjname"]];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        ProgressDismiss;
        [self.tableView removeFromSuperview];
    }];
}

#pragma mark 请求支持者数据
-(void)requestSupporterdata{
    NSLog(@"pid = %@",self.pid);
    [NetworkManager requestFoundingGetOneSponsorWithId:self.pid Mid:UserModel.mid password:UserModel.password pagecount:@"0" success:^(NSDictionary *dictResponse) {
        sponsorArray = [[dictResponse objectForKey:@"content"] mutableCopy];
        [self.collectionView reloadData];
        
        if (datadictionary.count>0) {
            NSIndexPath *indexSet=[NSIndexPath indexPathForItem:0 inSection:2];
            ZCProjectdetailallinfoCell *cell = [self.tableView cellForRowAtIndexPath:indexSet];
            cell.countLable.text =[NSString stringWithFormat:@"%lu人已支持",(unsigned long)sponsorArray.count];
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexSet] withRowAnimation:UITableViewRowAnimationNone];

        }
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark UIcollectionView

-(void)initcollectionView{
    
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    flowLayout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH,self.tableView.bounds.size.height);//头部
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    //设置代理
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    [self.collectionView setContentInset:UIEdgeInsetsMake(0, 0, 20, 0)];
    
    //注册cell和ReusableView（相当于头部）collectioncell
    [self.collectionView registerNib:[UINib nibWithNibName:@"ZCProjectdetailsCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"collectioncell"];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ReusableView"];

}

#pragma mark -- UICollectionViewDataSource

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [sponsorArray count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identify = @"collectioncell";
    ZCProjectdetailsCollectionCell *cell =(ZCProjectdetailsCollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    NSDictionary *dict = (NSDictionary *)sponsorArray[indexPath.row];
    cell.nameLable.text = [NSString stringWithFormat:@"%@",[dict objectForKey:@"mid"]];
    
    NSInteger money = [[dict objectForKey:@"money"]intValue]/100;
    cell.priceLable.text =[NSString stringWithFormat:@"￥%ld",money];
    cell.priceLable.textColor = [UIColor orangeColor];
    int timeInt =[[NSString stringWithFormat:@"%@",[dict objectForKey:@"paytime"]] intValue];
    cell.timelable.text = [NSString stringWithFormat:@"%@",stringDataWithTimeInterval(timeInt)];
        return cell;
}
//头部显示的内容
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:
                                            UICollectionElementKindSectionHeader withReuseIdentifier:@"ReusableView" forIndexPath:indexPath];
    
    [headerView addSubview:self.tableView];//头部广告栏
    return headerView;
}
#pragma mark --UICollectionViewDelegateFlowLayout
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((SCREEN_WIDTH-40)/2, 90);
}
//定义每个UICollectionView 的间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 15, 0, 15);
}
//定义每个UICollectionView 纵向的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}
#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //    UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    //    cell.backgroundColor = [UIColor redColor];
    NSLog(@"选择%ld",(long)indexPath.row);
}
//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}


#pragma mark TableViewHeaderView

-(void)initTableViewHeaderView{
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,44)];
    headView.backgroundColor = [UIColor whiteColor];
    
    self.titlenameLable = [UILabel new];
    [headView addSubview:self.titlenameLable];
    self.titlenameLable.font = [UIFont systemFontOfSize:16];
    self.titlenameLable.textAlignment = NSTextAlignmentCenter;
    [self.titlenameLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(headView.mas_centerX);
        make.centerY.equalTo(headView.mas_centerY);
        make.width.mas_equalTo(@(SCREEN_WIDTH));
        make.height.mas_equalTo(@(30));
    }];
    self.tableView.tableHeaderView = headView;
}

-(void)initTableView{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 627) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.sectionFooterHeight = 0.0001;
    self.tableView.scrollEnabled = NO;

}

#pragma mark UITableViewDataSource,UITableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    NSLog(@"count11 ===%ld",[datadictionary count]);
    return [datadictionary count];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if([datadictionary count]>0){
        if (section==3) {
            return 2;
        }else{
            return 1;
        }
    }else{
        return 0;
    }
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ZCProjectdetailsModel *detailsmodel = [ZCProjectdetailsModel modelObjectWithDictionary:datadictionary];
    
    if (indexPath.section==0) {
        ZCprojectdetailinfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"info"];
        cell.detailesModel = detailsmodel;
        return cell;
    }else if (indexPath.section==1){
        ZCProjectResultCell *cell = [tableView dequeueReusableCellWithIdentifier:@"result"];
        cell.delegate = self;
        cell.resultStr = [NSString stringWithFormat:@"%@",detailsmodel.result];
        cell.testreportidStr = [NSString stringWithFormat:@"%@",detailsmodel.testreportid];
        return cell;
    }else if(indexPath.section==2){
        ZCProjectdetailallinfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"allinfo"];
        NSInteger money = [[NSString stringWithFormat:@"%@",detailsmodel.emoney]integerValue]/100;
        cell.emoneyLable.text = [NSString stringWithFormat:@"￥%ld 已筹齐",money];
        cell.countLable.text = [NSString stringWithFormat:@"%lu人已支持",(unsigned long)sponsorArray.count];
        return cell;
    }else if(indexPath.section==3){
        if (indexPath.row==0) {
            ZCProjectdetailSamplingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"sampling"];
            cell.nameLable.text = [NSString stringWithFormat:@"%@已完成抽样",detailsmodel.institution];
            cell.countLable.text = [NSString stringWithFormat:@"%@",detailsmodel.samnum];
            return cell;
        }else{
            ZCProjectdetailSamplingTwoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"samplingtwo"];
            return cell;
        }
    }else{
        ZCProjectdetailSamplingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"sampling"];
        [cell.contentView removeFromSuperview];
        return cell;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        return 148;
    }else if (indexPath.section==1){
        return 85;
    }else if(indexPath.section==2){
        return 50;
    }else if(indexPath.section==3){
        if (indexPath.row==0) {
            return 80;
        }else{
            return 44;
        }
    }else{
        return 10;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==1) {
        return 10;
    }else{
        return 40;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section==1) {
        UIView * headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
        headView.backgroundColor = [UIColor colorWithHexString:@"#ebeded"];
        return headView;
        
    }else{
        NSArray *titleArray = [NSArray arrayWithObjects:@"基本信息",@"众筹信息",@"抽样信息",@"支持者",nil];
        UIView * headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        headView.backgroundColor = [UIColor whiteColor];
        UIView *bgheadView = [UIView new];
        [headView addSubview:bgheadView];
        bgheadView.backgroundColor = [UIColor colorWithHexString:@"#ebeded"];
        [bgheadView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(headView.top).with.offset(0);
            make.left.equalTo(headView).with.offset(0);
            make.right.equalTo(headView).with.offset(0);
            make.height.mas_equalTo(@10);
        }];
        
        UIView *newView = [UIView new];
        [headView addSubview:newView];
        [newView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(headView.top).with.offset(10);
            make.left.equalTo(headView).with.offset(0);
            make.right.equalTo(headView).with.offset(0);
            make.bottom.equalTo(headView).with.offset(0);
        }];
        
        UILabel *leftlable = [UILabel new];
        [newView addSubview:leftlable];
        leftlable.font = [UIFont systemFontOfSize:16];
        if (section==0) {
            [leftlable setText:titleArray[0]];
        }else{
            [leftlable setText:titleArray[(section-1)]];
        }
//        [leftlable setText:@"最新检测结果"];
        [leftlable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(newView.mas_centerY);
            make.left.equalTo(newView).with.offset(15);
            make.height.mas_equalTo(@30);
            make.width.mas_equalTo(@150);
        }];
        return headView;
    }
    
}

#pragma mark 分享点击
-(void)shareButtonPressed:(id *)button{
    CGFloat xWidth = self.view.bounds.size.width - 10.0f;
    CGFloat yHeight = 120.0f;
    UIsharePopoverListView *poplistview = [[UIsharePopoverListView alloc] initWithFrame:CGRectMake(0,0, xWidth/2, yHeight)];
    poplistview.delegate = self;
    poplistview.listView.scrollEnabled = FALSE;
    [poplistview show];
}
- (void)popoverListView:(UIsharePopoverListView *)popoverListView
     didSelectIndexPath:(NSIndexPath *)indexPath{
  
    
    [NetworkManager requestFoundingGetShareWithMid:UserModel.mid password:UserModel.password fdid:self.pid success:^(NSDictionary *dictResponse) {
        
        NSLog(@"dict = %@",dictResponse);
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = [NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"title"]];
        NSLog(@"mesage.title = %@",message.title);
        message.description = [NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"desc"]];
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"imgUrl"]]]];
        message.thumbData = data;
        
        WXWebpageObject *ext = [WXWebpageObject object];
        ext.webpageUrl = [NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"link"]];;
        
        message.mediaObject = ext;
        SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.message = message;
        if (indexPath.row == 0) {
            req.scene = WXSceneTimeline;
            [WXApi sendReq:req];
        } else if (indexPath.row == 1) {
            req.scene = WXSceneSession;
            [WXApi sendReq:req];
        }

    } failure:^(NSError *error) {
        
    }];
}

#pragma mark 点击查看检测书
-(void)ClocklookResult{
    ZCProjectdetailsModel *detailsmodel = [ZCProjectdetailsModel modelObjectWithDictionary:datadictionary];
    ZCLookResultVC *lookvc = [[ZCLookResultVC alloc]init];
    lookvc.nameStr = detailsmodel.pjname;
    lookvc.url = [NSString stringWithFormat:@"%@%@",[NetworkManager strURLBasic],detailsmodel.testreport];
    lookvc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:lookvc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
